<template>
  <div class="login-container">
    <el-card class="login-card" shadow="always">
      <div class="login-header">
        <el-icon class="login-icon" :size="48">
          <User />
        </el-icon>
        <h1 class="login-title">员工管理系统</h1>
        <p class="login-subtitle">欢迎登录后台管理</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="formRules"
        class="login-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入账号"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">
            记住我
          </el-checkbox>
        </el-form-item>
<!--        登录按钮-->
        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="isLoading"
            :disabled="!isFormValid"
            @click="handleLogin"
          >
            <el-icon v-if="!isLoading"><Right /></el-icon>
            {{ isLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <el-alert
          title="演示账号: admin / 123456"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed, nextTick} from 'vue'
  import { ElNotification } from 'element-plus'
  import { User, Lock, Right } from '@element-plus/icons-vue'
  //引入用户仓库
  import useUserStore from '@/stores/modules/user'
  let userStore = useUserStore()
  //获取路由器
  import { useRouter,useRoute} from 'vue-router';
  let $router = useRouter();
  let $route = useRoute();

  // 表单引用
  const loginFormRef = ref()

  // 登录表单数据
  const loginForm = reactive({
    username: 'admin',
    password: '123456',
    rememberMe: false
  })

  // 控制状态
  const isLoading = ref(false)

  const validatorUserName = (rule: any, value: any,callback: any) => {
    if (value.length >= 5) {
      callback();//callback() 用于放行验证，只有执行了 callback()，表单验证才会通过，允许执行后续代码。如果验证失败，应调用 callback(new Error('错误信息')) 阻止后续代码执行。
    } else {
      callback(new Error('账号长度至少五位'));
    }
  }

  const validatorPassword = (rule: any, value: any,callback: any) => {
    if (value.length >= 6) {
      callback();//callback() 用于放行验证，只有执行了 callback()，表单验证才会通过，允许执行后续代码。如果验证失败，应调用 callback(new Error('错误信息')) 阻止后续代码执行。
    } else {
      callback(new Error('密码长度至少六位'));
    }
  }

  // Element Plus表单验证规则
  const formRules = {
    username: [
      {validator:validatorUserName, trigger: 'change'}
    ],
    password: [
      {validator:validatorPassword, trigger: 'change'}
    ]
  }

  // 表单是否有效(表单无效是不允许登录的)
  const isFormValid = computed(() => {
    return loginForm.username.trim() && loginForm.password.trim()
  })

  // 处理登录
  const handleLogin = async () => {
    try {
      // 验证整个表单
      await loginFormRef.value.validate();
      isLoading.value = true;

      // 真实登录
      await userStore.userLogin(loginForm);

      // 保存记住我状态
      if (loginForm.rememberMe) {
        localStorage.setItem('rememberedUsername', loginForm.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }

      // 登录成功提示
      ElNotification({
        type: 'success',
        message: '登录成功！',
      })

      // 等待一下确保状态更新，然后跳转
      await nextTick()

      let redirect = $route.query.redirect as string
      await $router.replace(redirect || '/')

    } catch (error) {
      console.error('登录失败:', error)
      ElNotification({
        type: 'error',
        message: '登录失败，请重试',
      })
    } finally {
      isLoading.value = false
    }
  }

  // 页面加载时检查是否有记住的用户名
  const checkRememberedUser = () => {
    const remembered = localStorage.getItem('rememberedUsername')
    if (remembered) {
      loginForm.username = remembered
      loginForm.rememberMe = true
    }
  }

  // 初始化
  checkRememberedUser()
</script>

  <style scoped>
    .login-container {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 20px;
    }

    .login-card {
      width: 100%;
      max-width: 420px;
      animation: fadeInUp 0.6s ease-out;
      border-radius: 16px !important;
    }

    .login-card :deep(.el-card__body) {
      padding: 40px;
    }

    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(30px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .login-header {
      text-align: center;
      margin-bottom: 32px;
    }

    .login-icon {
      color: #409eff;
      margin-bottom: 16px;
    }

    .login-title {
      font-size: 28px;
      font-weight: 700;
      color: #2d3748;
      margin: 0 0 8px 0;
    }

    .login-subtitle {
      font-size: 16px;
      color: #718096;
      margin: 0;
    }

    .login-form {
      margin-bottom: 20px;
    }

    .login-form :deep(.el-form-item) {
      margin-bottom: 24px;
    }

    .login-form :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.3s ease;
    }

    .login-form :deep(.el-input__wrapper:hover) {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }

    .login-form :deep(.el-input.is-focus .el-input__wrapper) {
      box-shadow: 0 0 0 1px #409eff inset;
    }

    .login-button {
      width: 100%;
      height: 48px;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      background: linear-gradient(135deg, #409eff 0%, #667eea 100%);
      border: none;
      transition: all 0.3s ease;
    }

    .login-button:hover {
      background: linear-gradient(135deg, #337ecc 0%, #5a6fd8 100%);
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(64, 158, 255, 0.3);
    }

    .login-button:active {
      transform: translateY(0);
    }

    .login-footer {
      margin-top: 20px;
    }

    .login-footer :deep(.el-alert) {
      border-radius: 8px;
      border: none;
      background: rgba(64, 158, 255, 0.1);
    }

    .login-footer :deep(.el-alert__title) {
      font-size: 14px;
      color: #409eff;
    }

    /* 响应式设计 */
    @media (max-width: 480px) {
      .login-container {
        padding: 16px;
      }

      .login-card :deep(.el-card__body) {
        padding: 24px;
      }

      .login-title {
        font-size: 24px;
      }
    }

    @media (max-width: 360px) {
      .login-card :deep(.el-card__body) {
        padding: 20px;
      }

      .login-title {
        font-size: 22px;
      }
    }
  </style>
